<template>
  <KView class="sys-home-div">
    <sys-scroll-view class="sys-home" :is-profile="currentPage==='circle'" @scrolltolower="scrolltolower" @open-profile="openProfile">
      <template v-if="isShow">
        <KView class="sys-header-div">
          <sys-header @search-click="searchClick" @location-change="locationChange"></sys-header>
        </KView>
        <KView class="sys-home-line sys-header-line"></KView>

        <sys-tabs class="sys-home-tabs" v-model="currentTab" :tabs="menuTabs" :before-click="beforeTabChange" @tab-change="tabChange">
          <template class="sys-home-pane" slot-scope="scope">
            <template v-if="['1','2','3'].indexOf(scope.tab.id)!==-1">
              <adv-comp v-if="advertiseData!==null" :img-urls="advertiseData.advertiseTopList" @item-clcik="openAd"></adv-comp>
            </template>
          </template>
        </sys-tabs>

        <template v-if="currentPage==='goods'">
          <home-classify class="sys-home-classify" :classify-list="classifyList" @menu-click="menuClick">
          </home-classify>

          <KView v-if="advertiseList!==null" class="sys-home-adv-center">
            <KView v-for="advertise in advertiseList" :key="'advertise'+advertise.id">
              <img class="sys-img" :src="advertise.imgUrl" mode="aspectFit" @click="openAd(advertise)">
            </KView>
          </KView>

          <KView class="sys-home-grass" v-if="recommendGoods.length>0">
            <KView class="sys-home-title">种草系列</KView>
            <KView class="sys-home-grass-content">
              <recommend-good-comp :goods-list="recommendGoods" :pagination="recommendGoodPagination" :next-data-fun="setRecommendGoods"
                @item-detail="toGoodsDetail" @buy-goods="buyGoods">
              </recommend-good-comp>
            </KView>
          </KView>
          <KView class="sys-home-line sys-grass-line"></KView>

          <KView class="sys-home-goodslist">
            <KView class="sys-home-title">{{goodsTabData.label}}</KView>
            <KView class="sys-home-goodslist-content">
              <goods-list-comp :goods-list="goodsList" :pagination="goodsListPagination" :loading="goodsLoading" @item-detail="toGoodsDetail">
              </goods-list-comp>
            </KView>
          </KView>
        </template>
        <template v-else-if="currentPage==='circle'">
          <KView class="sys-home-line sys-grass-line"></KView>
          <KView class="sys-home-circle-div">
            <KView class="sys-home-title">{{goodsTabData.label}}</KView>
            <KView class="sys-home-line home-circle-div-line"></KView>
            <home-circle ref="homeCircle"></home-circle>
          </KView>
        </template>
      </template>
    </sys-scroll-view>

    <goods-model-dialog :visible.sync="openDialog" :goods="selectGoods" @close="dialogClose">
    </goods-model-dialog>
  </KView>
</template>

<script>
  import Pagination from 'models/pagination';
  import HomePageApi from 'services/homePageApi';

  import SysScrollView from 'common/sysScrollView';
  import SysTabs from 'common/sysTabs';
  import GoodsModelDialog from 'views/shopMall/shopGoods/goodsModelDialog';
  import SysHeader from '../systemIndex/header';
  import AdvComp from './advComp';
  import HomeClassify from './homeClassify';
  import RecommendGoodComp from './recommendGoodComp';
  import GoodsListComp from './goodsListComp';
  import HomeCircle from './homeCircle';

  import MapUtil from 'utils/mapUtil';
  import SystemUtil from 'utils/systemUtil';

  import storeMixins from 'mixins/storeMixins';

  export default {
    mixins: [storeMixins],

    computed: {
      advertiseList() {
        let advertiseData = this.advertiseData;
        if (advertiseData === null) {
          return null;
        }
        let advertiseBottomList = advertiseData.advertiseBottomList;
        if (advertiseBottomList.length === 0) {
          return null;
        }
        return advertiseBottomList;
      },

      goodsTabData() {
        let menuTabs = this.menuTabs;
        let id = this.currentTab;
        let tab = menuTabs.find(obj => obj.id === id);
        return tab;
      }
    },

    watch: {
      user() {
        this.setMenuTabs();
      }
    },

    data() {
      return {
        isMiniprogram: process.env.isMiniprogram,
        isShow: false,
        location: null,
        advertiseData: null,
        currentTab: '1',
        currentPage: 'goods',
        menuTabs: [{
          id: '1',
          label: '到店自取'
        }, {
          id: '2',
          label: '配送到家'
        }],
        classifyList: [],
        recommendGoods: [],
        recommendGoodPagination: new Pagination(),
        goodsList: [],
        goodsListPagination: new Pagination(),
        goodsLoading: false,
        openDialog: false,
        selectGoods: null
      };
    },

    created() {
      this.initData();

      window.onShareAppMessage = data => {
        let from = data.from;
        if (from === 'menu') {
          return {
            path: '/home'
          };
        }
        let id = data.target.id;
        if (id.indexOf('type_') !== 0) {
          return {
            path: '/home'
          };
        }
        let shareData = this.$refs['homeCircle'].getShareData(id);
        return shareData;
      };
    },

    methods: {
      initData() {
        SystemUtil.showLoading();
        this.setSysLocationData().then(location => {
          return window.Promise.all([
            this.setAdvertiseData(),
            this.setClassifyList(),
            this.setRecommendGoods(true),
            this.setGoodsList(true)
          ]).then(res => {
            SystemUtil.hideLoading();
            this.setMenuTabs();
            this.isShow = true;
          });
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      setMenuTabs() {
        let menuTabs = [{
          id: '1',
          label: '到店自取'
        }, {
          id: '2',
          label: '配送到家'
        }];

        if (this.user !== null) {
          menuTabs.push({
            id: '3',
            label: '漫淘圈'
          }, {
            id: '4',
            label: '优惠券'
          });
        }
        this.menuTabs = menuTabs;
      },

      setSysLocationData() {
        let user = this.user;
        if (user === null) {
          user = this.defaultUser;
        }
        return MapUtil.getLocationData(user).then(location => {
          this.location = location;
          this.setLocation(location);
          return location;
        });
      },

      setAdvertiseData() {
        return HomePageApi.getAdvertiseData().then(advertiseData => {
          this.advertiseData = advertiseData;
          return advertiseData;
        });
      },

      setClassifyList() {
        return HomePageApi.getHomeClassifyType().then(classifyList => {
          this.classifyList = classifyList;
          return classifyList;
        });
      },

      setRecommendGoods(isInit) {
        let goodsTabData = this.goodsTabData;
        let type = goodsTabData.id;
        return HomePageApi.getRecommendGoods(this.location, this.recommendGoodPagination, type).then(goodsList => {
          if (isInit) {
            this.recommendGoods = goodsList;
          } else {
            this.recommendGoods.push(...goodsList);
          }
          return goodsList;
        });
      },

      setGoodsList(isInit) {
        let goodsTabData = this.goodsTabData;
        let type = goodsTabData.id;
        return HomePageApi.getGoodsList(this.location, this.goodsListPagination, type).then(goodsList => {
          if (isInit) {
            this.goodsList = goodsList;
          } else {
            this.goodsList.push(...goodsList);
          }
          return goodsList;
        });
      },

      scrolltolower() {
        if (this.currentPage !== 'goods') {
          return;
        }
        if (this.goodsLoading) {
          return;
        }
        let pagination = this.goodsListPagination;
        if (!pagination.hasNextPage()) {
          return;
        }

        pagination.nextPage();
        this.goodsLoading = true;
        this.$nextTick(() => {
          this.setGoodsList().then(() => {
            this.goodsLoading = false;
          }).catch(() => {
            this.goodsLoading = false;
          });
        });
      },

      beforeTabChange(tab) {
        let id = tab.id;
        if (id !== '4') {
          return true;
        }

        let url = '/couponPage';
        if (this.isMiniprogram) {
          window.open(url);
        }
        return false;
      },

      tabChange() {
        let currentTab = this.currentTab;
        if (['4'].indexOf(currentTab) !== -1) {
          return;
        }

        if (currentTab === '3') {
          this.currentPage = 'circle';
          return;
        }

        this.recommendGoodPagination = new Pagination();
        this.goodsListPagination = new Pagination();
        SystemUtil.showLoading();
        window.Promise.all([
          this.setRecommendGoods(true),
          this.setGoodsList(true)
        ]).then(res => {
          this.currentPage = 'goods';
          SystemUtil.hideLoading();
        }).catch(() => {
          SystemUtil.hideLoading();
        });
      },

      openAd(advertise) {
        let href = advertise.href;
        if (href.trim() === '') {
          return;
        }

        let url;
        if (href.startsWith('http://') || href.startsWith('https://')) {
          url = `/htmlPage?url=${href}`;
        } else {
          url = href;
        }

        if (this.isMiniprogram) {
          window.open(url);
        }
      },

      menuClick(menu) {
        let path = menu.path;
        if (path === '') {
          SystemUtil.alert('即将开放，敬请期待！', '提示');
          return;
        }

        if (this.isMiniprogram) {
          if (menu.hasNav) {
            window.open(path);
          } else {
            this.$emit('to-page', path);
          }
        }
      },

      toGoodsDetail(goods) {
        let defId = goods.defId;
        if (SystemUtil.isEmpty(defId)) {
          return;
        }

        if (this.isMiniprogram) {
          window.open(`/goodsDetail/${defId}`);
        } else {
          this.$router.push({
            path: `/goodsDetail/${defId}`
          });
        }
      },

      buyGoods(goods) {
        this.selectGoods = goods;
        this.openDialog = true;
      },

      dialogClose() {
        this.selectGoods = null;
      },

      searchClick() {
        if (this.isMiniprogram) {
          window.open('/searchGoods');
        }
      },

      locationChange() {
        this.tabChange();
      },

      openProfile() {
        if (this.isMiniprogram) {
          window.open('/personalCircle');
        }
      },

      resetCircleZoneById(circleZone) {
        if (this.currentPage === 'circle') {
          this.$refs['homeCircle'].resetCircleZoneById(circleZone);
        }
      },

      resetCircleZoneLogById(logData) {
        if (this.currentPage === 'circle') {
          this.$refs['homeCircle'].resetCircleZoneLogById(logData);
        }
      },

      resetCircleZoneLog(spaceId) {
        if (this.currentPage === 'circle') {
          this.$refs['homeCircle'].resetCircleZoneLog(spaceId);
        }
      }
    },

    components: {
      SysScrollView,
      SysHeader,
      SysTabs,
      AdvComp,
      HomeClassify,
      RecommendGoodComp,
      GoodsListComp,
      GoodsModelDialog,
      HomeCircle
    }
  };

</script>

<style lang="scss">
  .sys-home-div {
    height: 100%;
  }

  .sys-home {
    height: 100%;
    overflow: auto;

    .sys-header-div {
      padding-top: formatPx(40);
      height: formatPx(70);
      padding-bottom: formatPx(45);
    }

    .sys-home-line {
      background: #DADADA;
    }

    .sys-header-line {
      height: 1px;
      margin-left: formatPx(-30);
      margin-right: formatPx(-30);
    }

    .sys-home-tabs {
      margin-top: formatPx(40);
      height: formatPx(482);
    }

    .sys-home-classify {
      margin-top: formatPx(50);
    }

    .sys-home-adv-center {
      margin-top: formatPx(50);

      >div {
        height: formatPx(180);
        overflow: hidden;
        border-radius: formatPx(90);
        margin-bottom: formatPx(20);

        &:last-child {
          margin-bottom: 0;
        }
      }
    }

    .sys-home-grass {
      margin-top: formatPx(55);

      .sys-home-grass-content {
        margin-top: formatPx(30);
        height: formatPx(355);
      }
    }

    .sys-home-title {
      border-left: formatPx(10) solid #59C264;
      font-size: formatPx(36);
      padding-left: formatPx(15);
      line-height: formatPx(40);
      height: formatPx(40);
    }

    .sys-grass-line {
      height: formatPx(18);
      margin-left: formatPx(-30);
      margin-right: formatPx(-30);
      margin-top: formatPx(45);
    }

    .sys-home-goodslist {
      margin-top: formatPx(45);

      .sys-home-title {
        margin-bottom: formatPx(30);
      }
    }

    .sys-home-circle-div {
      margin-top: formatPx(45);

      .home-circle-div-line {
        height: 1px;
        margin-top: formatPx(30);
        margin-bottom: formatPx(30);
      }
    }
  }

</style>
